package com.springsecurity.service;

import com.springsecurity.mapper.UserMapper;
import com.springsecurity.pojo.Menu;
import com.springsecurity.pojo.Role;
import com.springsecurity.pojo.User;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
@Service
public class UserService implements UserDetailsService{
	@Resource
	UserMapper userMapper;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user=userMapper.findByUsername(username);
		if (user==null) {
			throw new UsernameNotFoundException("账号不存在");
		}
		user.setRoles(userMapper.findRolesByUserId(user.getUid()));
		Collection<GrantedAuthority> authorities=new ArrayList<>();
		for (Role role : user.getRoles()) {
			authorities.add(new SimpleGrantedAuthority(role.getName()));
			for (Menu menu : role.getMenus()) {
				authorities.add(new SimpleGrantedAuthority(menu.getMenuname()));
			}
		}
		return new org.springframework.security.core.userdetails.User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),authorities);
	}
}
